package com.wr.service;

import com.wr.handler.UserServerHandler;
import com.wr.service.com.wr.request.RpcRequest;
import com.wr.service.com.wr.serializer.JSONSerializer;
import com.wr.service.com.wr.serializer.RpcDecoder;
import com.wr.service.com.wr.serializer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 王瑞
 * @description: TODO
 * @date 2020/3/20  22:49
 */

@Service
public class UserServiceImpl implements UserService {
    @Override
    public String sayHello(String rpcRequest) {
        System.out.println("服务端方法被调用:");
        return "success";
    }

    public static void startServer(String inetHost, int inetPort) throws InterruptedException {
        NioEventLoopGroup bossgroup = new NioEventLoopGroup();    //接收请求的线程池
        NioEventLoopGroup workgroup = new NioEventLoopGroup();    //处理请求的线程池

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossgroup, workgroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));    //自定义解码器
                        pipeline.addLast(new UserServerHandler());   // 服务端处理请求的核心方法类
                    }
                });

        bootstrap.bind(inetHost,inetPort).sync();

    }
}
